package cn.kgc.easybuy.config;

import cn.kgc.easybuy.listener.OrderExpirationListener;
import cn.kgc.easybuy.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * redis监听order状态
 */
@Configuration
public class OrderListenByRedisConfig {

    private final RedisConnectionFactory redisConnectionFactory;

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    public OrderListenByRedisConfig(RedisConnectionFactory redisConnectionFactory) {
        this.redisConnectionFactory = redisConnectionFactory;
    }

    // 容器
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(){
        RedisMessageListenerContainer container =new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        // 只监听 "所有键" 前缀的过期键
        container.addMessageListener(orderExpirationListener(container),new PatternTopic("__keyevent@*__:expired"));
        return container;
    }

    @Bean
    public OrderExpirationListener orderExpirationListener(RedisMessageListenerContainer container){
        return new OrderExpirationListener(container, orderService, redisTemplate);
    }
}
